package lumis.service.wsrp.producer;

import lumis.portal.dao.DaoException;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.transaction.ITransaction;
import lumis.portal.transaction.PortalTransactionFactory;
import lumis.service.wsrp.common.WSRPUtils;

import com.sun.portal.wsrp.common.stubs.v2.AccessDenied;
import com.sun.portal.wsrp.common.stubs.v2.AccessDeniedFault;
import com.sun.portal.wsrp.producer.Producer;
import com.sun.portal.wsrp.producer.ProducerException;

/**
 * WSRP Producer utility class.
 *
 * @version $Revision: 13092 $ $Date: 2011-05-28 18:19:06 -0300 (Sat, 28 May 2011) $
 * @since 6.0.0
 */
public class WSRPProducerUtils extends WSRPUtils
{
    /**
     * Validate if the portletHandle is valid for a certain producer.
     * @param producer to validate the registrationHandle on.
     * @param portletHandle to be validated.
     * @throws AccessDenied if the handle is not associated to the producer.
     * @throws ProducerException is there is a problem during the process.
     */
	public static void validate(Producer producer, String portletHandle) throws AccessDenied, ProducerException 
	{
		ProducerImpl impl = (ProducerImpl) producer;
		
		for (OfferedPortlet offeredPortlet : impl.getOfferedPortlets()) 
		{
			if(offeredPortlet.getInterfaceInstanceId().equals(portletHandle))
			{
				return;
			}
		}
		ITransaction transaction = PortalTransactionFactory.createTransaction();
		try
		{
			try
			{
				transaction.begin();
				ClonedPortlet clonedPortlet = ManagerFactory.getEntityManager().find(ClonedPortlet.class, portletHandle);
				if(clonedPortlet == null)
				{
					throw new AccessDenied("Invalid Portlet Handle: " + portletHandle, new AccessDeniedFault());
				}
				transaction.commit();
			}
			finally
			{
				transaction.dispose();
			}
		} 
		catch (DaoException e) 
		{
			throw new ProducerException(e);
		}		
	}
}
